﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;

namespace SharePointPOBox.SendedFilesWebPart
{
    /// <summary>WebPart that show all items related to sended file</summary>
    [ToolboxItemAttribute(false)]
    public class SendedFilesWebPart : WebPart
    {
        #region variables

        /// <summary>GridView that shows all items related to sended file</summary>
        protected SPGridView gvMain;

        #endregion variables

        #region events
        
        /// <summary>CreateChildControls</summary>
        protected override void CreateChildControls()
        {
            SPList defaultLib = Common.GetLibrary(Common.DefaultLibraryURL, false);
            if (defaultLib == null || !defaultLib.DoesUserHavePermissions(SPBasePermissions.AddListItems))
            {
                return;
            }

            gvMain = new SPGridView
            {
                AutoGenerateColumns = false,
                Width = new Unit("100%")
            };
            gvMain.AlternatingRowStyle.CssClass = "ms-alternating";

            // Create column that show file icon
            TemplateField tmpfldIcon = new TemplateField()
            {
                HeaderImageUrl
                    = SPContext.Current.Web.Url + "/_layouts/images/blank.gif",
                ShowHeader = true
            };
            tmpfldIcon.ItemTemplate = new FileIconFieldTemplate();
            tmpfldIcon.HeaderStyle.CssClass = "ms-vh-icon";
            tmpfldIcon.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            tmpfldIcon.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            gvMain.Columns.Add(tmpfldIcon);

            // Create column that show item title
            TemplateField bfldTitle = new TemplateField()
            {
                ItemTemplate = new TitleFieldTemplate(),
                HeaderText = Common.CurLngStr("SPPOBSendedFilesWebPart_FileNameTitle")
            };
            gvMain.Columns.Add(bfldTitle);

            // Create column that show download limit
            TemplateField bfldDLCount = new TemplateField()
            {
                ItemTemplate = new SPListItemFieldTemplate("DownloadLimit"),
                HeaderText = Common.CurLngStr("SPPOBSendedFilesWebPart_DownladTimesTitle")
            };
            bfldDLCount.ItemStyle.HorizontalAlign
                = System.Web.UI.WebControls.HorizontalAlign.Center;
            gvMain.Columns.Add(bfldDLCount);

            // Create column that show download deadline
            TemplateField bfldExpire = new TemplateField()
            {
                ItemTemplate = new SPListItemFieldTemplate("DownloadDeadline"),
                HeaderText = Common.CurLngStr("SPPOBSendedFilesWebPart_ExpirationTitle")
            };
            bfldExpire.ItemStyle.HorizontalAlign
                = System.Web.UI.WebControls.HorizontalAlign.Center;
            gvMain.Columns.Add(bfldExpire);

            // Create column that show icon to open download page
            TemplateField tmpfldOpnDlPage = new TemplateField()
            {
                HeaderText = "URL",
                ItemTemplate = new OpenDlPageFieldTemplate()
            };
            tmpfldOpnDlPage.ItemStyle.HorizontalAlign
                = System.Web.UI.WebControls.HorizontalAlign.Center;
            gvMain.Columns.Add(tmpfldOpnDlPage);

            // Create column that show icon to copy password to clipboard 
            TemplateField tmpfldPass = new TemplateField()
            {
                ItemTemplate = new PasswordFieldTemplate(),
                HeaderText = Common.CurLngStr("SPPOBSendedFilesWebPart_PasswordTitle")
            };
            tmpfldPass.ItemStyle.HorizontalAlign
                = System.Web.UI.WebControls.HorizontalAlign.Center;
            gvMain.Columns.Add(tmpfldPass);

            // Create column that show icon to create mail
            TemplateField tmpfldMailTo = new TemplateField()
            {
                HeaderText = "Mail",
                ItemTemplate = new MailtoFieldTemplate()
            };
            tmpfldMailTo.ItemStyle.HorizontalAlign
                = System.Web.UI.WebControls.HorizontalAlign.Center;
            gvMain.Columns.Add(tmpfldMailTo);

            // Create column that show icon to property item
            TemplateField tmpfldProperty = new TemplateField()
            {
                ItemTemplate = new PropertyFieldTemplate(),
                HeaderText = Common.CurLngStr("SPPOBSendedFilesWebPart_PropertyTitle")
            };
            tmpfldProperty.ItemStyle.HorizontalAlign
                = System.Web.UI.WebControls.HorizontalAlign.Center;
            gvMain.Columns.Add(tmpfldProperty);

            // Create column that show icon to delete item
            TemplateField tmpfldDelete = new TemplateField()
            {
                ItemTemplate = new DeleteFieldTemplate(),
                HeaderText = Common.CurLngStr("SPPOBSendedFilesWebPart_DeleteTitle")
            };
            tmpfldDelete.ItemStyle.HorizontalAlign
                = System.Web.UI.WebControls.HorizontalAlign.Center;
            gvMain.Columns.Add(tmpfldDelete);


            this.Controls.Add(gvMain);
            gvMain.DataSource = GetData();
            gvMain.DataBind();

            this.Controls.Add(new ScriptLink()
            {
                Name = "~sitecollection/_layouts/SharePointPOBox/SPPOBSendToPOBox.js",
                Language = "javascript"
            });
        }

        #endregion events

        #region methods 

        /// <summary>All items related to sended files</summary>
        private SPListItemCollection GetData()
        {
            if (Common.ManageList == null) return null;

            SPQuery qry = new SPQuery()
            {
                Query = "<Where>"
                        + "<And>"
                            + "<IsNotNull><FieldRef Name='DownloadKey' /></IsNotNull>"
                            + "<And>"
                                + "<BeginsWith>"
                                    + "<FieldRef Name='ContentTypeId' />"
                                    + "<Value Type='Text'>"
                                        + Common.DownloadItemContentTypeId
                                    + "</Value>"
                                + "</BeginsWith>"
                                + "<Geq>"
                                    + "<FieldRef Name='DownloadDeadline' />"
                                    + "<Value Type='DateTime'>"
                                        + SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now)
                                    + "</Value>"
                                + "</Geq>"
                            + "</And>"
                        + "</And>"
                        + "</Where>"
                        + "<OrderBy>"
                            + "<FieldRef Name='DownloadDeadline' Ascending='TRUE' />"
                        + "</OrderBy>",
                RowLimit = 100,
                ViewFields
                    = "<FieldRef Name='ID'/>"
                    + "<FieldRef Name='Title'/>"
                    + "<FieldRef Name='DownloadKey'/>"
                    + "<FieldRef Name='DownloadDeadline'/>"
                    + "<FieldRef Name='Author' />"
                    + "<FieldRef Name='Purpose'/>"
                    + "<FieldRef Name='Password'/>"
                    + "<FieldRef Name='DownloadLimit'/>"
                    + "<FieldRef Name='FileUrl'/>"
            };
            SPListItemCollection itmRet = Common.ManageList.GetItems(qry);

            return itmRet;
        }

        #endregion methods

        #region classes

        /// <summary>Template that show file icon</summary>
        protected class FileIconFieldTemplate : ITemplate
        {
            public void InstantiateIn(Control container)
            {
                HtmlImage imgIcon = new HtmlImage();
                imgIcon.DataBinding += new EventHandler(imgIcon_DataBinding);
                container.Controls.Add(imgIcon);
            }

            void imgIcon_DataBinding(object sender, EventArgs e)
            {
                HtmlImage imgIcon = (HtmlImage)sender;
                GridViewRow row = (GridViewRow)imgIcon.NamingContainer;
                SPListItem item = (SPListItem)row.DataItem;
                imgIcon.Src
                    = SPContext.Current.Web.Url + "/_layouts/images/" + SPUtility.MapToIcon(SPContext.Current.Web, item.Title, string.Empty, IconSize.Size16);
            }
        }

        /// <summary>Template that show 'Title' value and donwload link</summary>
        protected class TitleFieldTemplate : ITemplate
        {
            public void InstantiateIn(Control container)
            {
                Label lb = new Label();
                lb.DataBinding += new EventHandler(lb_DataBinding);
                HtmlAnchor lnk = new HtmlAnchor();
                lnk.DataBinding += new EventHandler(lnk_DataBinding);
                lnk.Controls.Add(lb);

                container.Controls.Add(lnk);
            }

            void lnk_DataBinding(object sender, EventArgs e)
            {
                HtmlAnchor lnk = (HtmlAnchor)sender;
                GridViewRow row = (GridViewRow)lnk.NamingContainer;
                SPListItem item = (SPListItem)row.DataItem;

                lnk.HRef
                    = (new SPFieldUrlValue(item[item.Fields.GetFieldByInternalName("FileUrl").Id].ToString())).Url;
                //lnk.HRef = "#";
                //using (SPWeb web = item.ParentList.ParentWeb)
                //{
                //    string dispFormUrl 
                //        = string.Format("{0}/{1}?ID={2}", web.Url, item.ParentList.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url, item.ID.ToString());
                //    lnk.Attributes.Add("onclick", "var options = {url: '" + dispFormUrl + "', title: '" + item.Title + "', dialogReturnValueCallback: Function.createDelegate(null, function(){}),allowMaximize: false,showClose: true};SP.UI.ModalDialog.showModalDialog(options);return false;");
                //}
            }

            void lb_DataBinding(object sender, EventArgs e)
            {
                Label lb = (Label)sender;
                GridViewRow row = (GridViewRow)lb.NamingContainer;
                SPListItem item = (SPListItem)row.DataItem;
                lb.Text = (string)item[item.Fields.GetFieldByInternalName("Title").Id];
            }
        }

        /// <summary>Template that show list item related to sended file</summary>
        protected class SPListItemFieldTemplate : ITemplate
        {
            private string _FieldInnerName;

            public SPListItemFieldTemplate(string FieldInnerName)
            {
                _FieldInnerName = FieldInnerName;
            }

            public void InstantiateIn(Control container)
            {
                Label lb = new Label();
                lb.DataBinding += new EventHandler(lb_DataBinding);
                container.Controls.Add(lb);
            }

            void lb_DataBinding(object sender, EventArgs e)
            {
                Label lb = (Label)sender;
                GridViewRow row = (GridViewRow)lb.NamingContainer;
                SPListItem item = (SPListItem)row.DataItem;

                object prop = item[item.Fields.GetFieldByInternalName(_FieldInnerName).Id];
                if (prop is DateTime)
                {
                    lb.Text = ((DateTime)prop).ToShortDateString();
                }
                else
                {
                    lb.Text = prop.ToString();
                }
            }
        }

        /// <summary>Template that show download password</summary>
        protected class PasswordFieldTemplate : ITemplate
        {
            public void InstantiateIn(Control container)
            {
                HtmlImage imgPassword = new HtmlImage();
                imgPassword.Src = "/_layouts/images/TABSEC.GIF";
                imgPassword.Alt = "Copy Password to Clipboard!";
                imgPassword.Attributes.Add("title", "Copy Password to Clipboard!");
                imgPassword.DataBinding += new EventHandler(imgPassword_DataBinding);
                container.Controls.Add(imgPassword);
            }

            void imgPassword_DataBinding(object sender, EventArgs e)
            {
                HtmlImage imgPassword = (HtmlImage)sender;
                GridViewRow row = (GridViewRow)imgPassword.NamingContainer;
                SPListItem item = (SPListItem)row.DataItem;
                if ((DateTime)item[item.Fields.GetFieldByInternalName("DownloadDeadline").Id] < DateTime.Today
                    || ((int)item[item.Fields.GetFieldByInternalName("DownloadLimit").Id] < 1))
                {
                    imgPassword.Visible = false;
                }
                else
                {
                    imgPassword.Attributes.Add(
                        "onclick"
                        , "clipboardData.setData('Text', '" + ((string)item[item.Fields.GetFieldByInternalName("Password").Id]).Replace("'", "\'") + "');alert('Password was sended to Clipboard!');");
                }
            }
        }

        /// <summary>Template that show popup link for download notice</summary>
        protected class MailtoFieldTemplate : ITemplate
        {
            public void InstantiateIn(Control container)
            {
                HtmlAnchor aMailToLink = new HtmlAnchor();
                aMailToLink.DataBinding += new EventHandler(aMailToLink_DataBinding);

                HtmlImage imgMailToLink = new HtmlImage();
                imgMailToLink.Src = "/_layouts/images/GMAILNEW.GIF";
                aMailToLink.Title
                    = imgMailToLink.Alt = SharePointPOBox.Common.CurLngStr("SPPOBMailTo");
                imgMailToLink.Style.Add(HtmlTextWriterStyle.BorderStyle, "none");
                aMailToLink.Controls.Add(imgMailToLink);

                container.Controls.Add(aMailToLink);
            }

            void aMailToLink_DataBinding(object sender, EventArgs e)
            {
                HtmlAnchor aMailToLink = (HtmlAnchor)sender;
                GridViewRow row = (GridViewRow)aMailToLink.NamingContainer;
                SPListItem item = (SPListItem)row.DataItem;
                if ((DateTime)item[item.Fields.GetFieldByInternalName("DownloadDeadline").Id] < DateTime.Today
                    || ((int)item[item.Fields.GetFieldByInternalName("DownloadLimit").Id] < 1))
                {
                    aMailToLink.Visible = false;
                }
                else
                {
                    aMailToLink.Attributes.Add("onclick"
                        , "ShowPopupSendToPOBoxDialog('" + SPContext.Current.Site.Url.TrimEnd("/".ToCharArray()) + "/_layouts/SharePointPOBox/Upload.aspx?id=" + item.ID.ToString() + "','" + Common.CurLngStr("SPPOBSendToPOBoxWebPart_DialogTitle") + "'); return false;");
                }
            }
        }

        /// <summary>Template that show button that to open download dialog</summary>
        protected class OpenDlPageFieldTemplate : ITemplate
        {
            public void InstantiateIn(Control container)
            {
                HtmlAnchor aOpenDlPage = new HtmlAnchor();
                aOpenDlPage.Target = "_blank";
                aOpenDlPage.DataBinding += new EventHandler(aOpenDlPage_DataBinding);
                container.Controls.Add(aOpenDlPage);

                HtmlImage imgOpenDlPage = new HtmlImage();
                imgOpenDlPage.Src = "/_layouts/images/DLDSLN16.PNG";
                aOpenDlPage.Title
                    = imgOpenDlPage.Alt = "Open";
                imgOpenDlPage.Style.Add(HtmlTextWriterStyle.BorderStyle, "none");
                aOpenDlPage.Controls.Add(imgOpenDlPage);
            }

            void aOpenDlPage_DataBinding(object sender, EventArgs e)
            {
                HtmlAnchor aOpenDlPage = (HtmlAnchor)sender;
                GridViewRow row = (GridViewRow)aOpenDlPage.NamingContainer;
                SPListItem item = (SPListItem)row.DataItem;
                if ((DateTime)item[item.Fields.GetFieldByInternalName("DownloadDeadline").Id] < DateTime.Today
                    || ((int)item[item.Fields.GetFieldByInternalName("DownloadLimit").Id] < 1))
                {
                    aOpenDlPage.Visible = false;
                }
                else
                {
                    aOpenDlPage.HRef
                        = aOpenDlPage.Title
                        = Common.CreateDownloadURL((string)item[item.Fields.GetFieldByInternalName("DownloadKey").Id]);
                }
            }
        }

        protected class PropertyFieldTemplate : ITemplate
        {
            public void InstantiateIn(Control container)
            {
                ImageButton imgbtnProperty = new ImageButton();
                imgbtnProperty.ImageAlign = ImageAlign.Middle;
                imgbtnProperty.ImageUrl = "/_layouts/images/TABSRCH.GIF";
                imgbtnProperty.DataBinding += new EventHandler(imgbtnProperty_DataBinding);
                container.Controls.Add(imgbtnProperty);
            }

            void imgbtnProperty_DataBinding(object sender, EventArgs e)
            {
                ImageButton imgbtnProperty = (ImageButton)sender;
                GridViewRow row = (GridViewRow)imgbtnProperty.NamingContainer;
                SPListItem item = ((SPListItem)row.DataItem);

                string dispFormUrl
                    = string.Format("{0}/{1}?ID={2}", item.Web.Url, item.ParentList.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url, item.ID.ToString());
                imgbtnProperty.OnClientClick
                    = "var options = {url: '" + dispFormUrl + "', title: '" + item.Title + "', dialogReturnValueCallback: Function.createDelegate(null, function(){}),allowMaximize: false,showClose: true};SP.UI.ModalDialog.showModalDialog(options);return false;";
            }
        }

        /// <summary>Template that show icon to delete item related to sended file</summary>
        protected class DeleteFieldTemplate : ITemplate
        {
            public void InstantiateIn(Control container)
            {
                ImageButton imgbtnDelete = new ImageButton();
                imgbtnDelete.ImageAlign = ImageAlign.Middle;
                imgbtnDelete.ImageUrl = "/_layouts/images/CRIT_16.GIF";
                imgbtnDelete.Command += new CommandEventHandler(imgbtnDelete_Command);
                imgbtnDelete.DataBinding += new EventHandler(imgbtnDelete_DataBinding);
                container.Controls.Add(imgbtnDelete);
            }

            void imgbtnDelete_Command(object sender, CommandEventArgs e)
            {
                SPListItem item = Common.ManageList.GetItemById(int.Parse((string)e.CommandArgument));
                item[item.Fields.GetFieldByInternalName("DownloadKey").Id] = string.Empty;
                bool preAllowUnsafeUpdates = item.Web.AllowUnsafeUpdates;
                item.Web.AllowUnsafeUpdates = true;
                item.Update();
                item.Web.AllowUnsafeUpdates = preAllowUnsafeUpdates;
                SPUtility.Redirect(HttpContext.Current.Request.RawUrl, SPRedirectFlags.Trusted, HttpContext.Current);
            }

            void imgbtnDelete_DataBinding(object sender, EventArgs e)
            {
                ImageButton imgbtnDelete = (ImageButton)sender;
                GridViewRow row = (GridViewRow)imgbtnDelete.NamingContainer;
                imgbtnDelete.CommandArgument = ((SPListItem)row.DataItem).ID.ToString();
                imgbtnDelete.OnClientClick
                    = "return confirm('" + string.Format(Common.CurLngStr("SPPOBSendedFilesWebPart_DeleteConfirmMessage"), ((SPListItem)row.DataItem).Title) + "');";
            }
        }

        #endregion classes
    }
}
